/*
 * Copyright 2013 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.univ.fblikes;

import org.apache.commons.lang3.StringUtils;
import org.springframework.social.facebook.api.Facebook;
import org.springframework.social.facebook.api.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.inject.Inject;
import java.util.List;
import java.util.logging.Logger;

/**
 * Simple little @Controller that invokes Facebook and renders the result.
 * The injected {@link Facebook} reference is configured with the required authorization credentials for the current user behind the scenes.
 */
@Controller
public class HomeController {
    private static final Logger LOGGER = Logger.getLogger(HomeController.class.getName());

    private final Facebook facebook;
    private final PostAnalyzer analyzer;
    private final int DEFAULT_DAYS = 1;

    @Inject
    public HomeController(Facebook facebook, PostAnalyzer analyzer) {
        this.facebook = facebook;
        this.analyzer = analyzer;
    }

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String myHome(Model model,
                         @RequestParam(value = "days", required = false, defaultValue = "1") int days) {
        return home(model, "me", days);
    }


    @RequestMapping(value = "/", method = RequestMethod.POST)
    public String myHome() {
        // Sometimes FB app is sending post request on the early start
        return "redirect:/";
    }


    @RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
    public String home(Model model, @PathVariable String id,
                       @RequestParam(value = "days", required = false, defaultValue = "1") int days) {
        String name = facebook.userOperations().getUserProfile(id).getName();

        List<Reference> friends = facebook.friendOperations().getFriends();
        List<Word> words = analyzer.getWordsStatistics(facebook, id, days);

        model.addAttribute("friends", friends);
        model.addAttribute("words", words);
        model.addAttribute("name", name);
        model.addAttribute("days", days);

        // Show home.jsp with updated model
        return "home";
    }

    @RequestMapping(value = "/postStatus", method = RequestMethod.GET)
    public String refreshAfterPost(Model model) {
        return myHome(model, DEFAULT_DAYS);
    }

    @RequestMapping(value = "/postStatus", method = RequestMethod.POST)
    public String post(Model model, @RequestParam("text") String text) {
        String res;
        String resClass;
        if (StringUtils.isEmpty(text)) {
            res = "Can't post empty message!";
            resClass = "error";
        } else {
            try {
                facebook.feedOperations().post("me", text);
                res = "Message successfully posted";
                resClass = "success";
            } catch (Exception e) {
                res = "Can't post message, something was wrong!";
                resClass = "error";
            }

        }

        model.addAttribute("actionResult", res);
        model.addAttribute("actionResultStyle", resClass);
        myHome(model, DEFAULT_DAYS);
        return "redirect:/";
    }

}
